package com.xunk.common.core.utils;


import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.TextCodec;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.SecretOptions;
import io.vertx.ext.auth.jwt.JWTAuth;
import io.vertx.ext.auth.jwt.JWTAuthOptions;
import io.vertx.ext.jwt.JWTOptions;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

public class JwtUtil {
  private static final String ALLCHAR = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  
  public static final long JWT_TERM_TOKEN = 2592000L;
  
  public static final long JWT_TERM_REQUEST = 1800L;
  
  private static final Vertx vertx = Vertx.vertx();
  
  private String privateKeyStr = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALNuM1L2Gk3ff02N0GTR9vfuJfZ3p4/dNgeqxqrGGKqdm6QvqVm8cwsGayImwuabpniBsmIOJNYcibThO0QofE08hYlDvHjGmAb6dajoOHLln+nHQfbaqqTo7wCReQUtBrfqFyXVIvexAWKxMMDiySuAGOZv13M3cBc9NsPJ0bJ/AgMBAAECgYBCLIBNNmpZEfY3OfgDVtRId9IUZeisTB8jEL6YONrcAahnExTX/YJILKPSQo1a00i/5MVPGHxJYtj+lppu9qdwjm+NpmJcFh0A6pWp7MDUnunQBG92Lp28jLZ1oUeOOuh2QwRL2nzLOnaYRnLIyS12ZlESlKJGhZA3l09dPf8ecQJBAOKAqeQRBu3OIjw93Rl9mp2R/gTllI7LWYwn6EtjhsvgUqv0HvTk3Pr3TXbsm3fq/8JnDtIVS3P+aV/ebKEXTCsCQQDKzDTT5vxm1QvUn6xuQNCH9bLWTMPt53AGosMI9SbopvHHNTw6dJHPtyR9XRZFlSgUIMpxf1opApTv2WIYsET9AkEAzigRedXNmrDeFDqyfTsHeZehvs8/MeEANkM0eTmzPOmGFaBydK/COmLRDQc6UiGAfG7U3H4pWQAc5PdLpCvSVQJBAJhX7xeAXfuh79E6Yf4xEnYQTNhPsp/1TGKvwnPoNeJwBxDvHN+M0jyICBFk7GY5NnJob6vzT3efSOMlGlwRjsECQEzVhVqPRvShj51JztgeRRwLQbwYZabY3B7+XqnWjTOVIK4/ipJKzzmsAUIBwsjLC9b3GRMsG1nQLYqvjlQvazM=";
  
  private String publicKeyStr = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCzbjNS9hpN339NjdBk0fb37iX2d6eP3TYHqsaqxhiqnZukL6lZvHMLBmsiJsLmm6Z4gbJiDiTWHIm04TtEKHxNPIWJQ7x4xpgG+nWo6Dhy5Z/px0H22qqk6O8AkXkFLQa36hcl1SL3sQFisTDA4skrgBjmb9dzN3AXPTbDydGyfwIDAQAB";
  
  private String secret;
  
  private SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
  
  private SignatureAlgorithm rsaSA = SignatureAlgorithm.RS512;
  
  public static String randomStr(int length) {
    StringBuffer sb = new StringBuffer();
    Random random = new Random();
    for (int i = 0; i < length; i++)
      sb.append(ALLCHAR.charAt(random.nextInt(ALLCHAR.length())));
    return sb.toString();
  }
  
  public static String getSignData(String token) {
    String[] tokens = token.split("\\.");
    return TextCodec.BASE64URL.decodeToString(tokens[1]);
  }
  
  public JwtUtil(String secret) {
    this.secret = secret;
  }
  
  public String createJWT4Subject(String subject) {
    return createJWT(null, null, subject, 100000L);
  }
  
  public String createJWT(String id, String issuer, String subject, long ttlSecond) {
    long nowMillis = System.currentTimeMillis();
    Date now = new Date(nowMillis);
    byte[] apiKeySecretBytes = Base64.decodeBase64(this.secret);
    Key signingKey = new SecretKeySpec(apiKeySecretBytes, 0, apiKeySecretBytes.length, "AES");
    JwtBuilder builder = Jwts.builder().setPayload(subject).signWith(this.signatureAlgorithm, signingKey);
    return builder.compact();
  }
  
  public Claims parseJWT(String jwt) {
    Claims claims = (Claims)Jwts.parser().setSigningKey(DatatypeConverter.parseBase64Binary(this.secret)).parseClaimsJws(jwt).getBody();
    return claims;
  }
  
  public static String getRuyingGwt(String secretOrKey) {
    return getRuyingGwt(secretOrKey, "hny");
  }
  
  public static String getRuyingGwt(String secretOrKey, String id) {
    return doRuyingGwt(secretOrKey, id);
  }
  
  private static String doRuyingGwt(String secretOrKey, String id) {
    SecretOptions options = (new SecretOptions()).setSecret(secretOrKey);
    List<SecretOptions> secrets = new ArrayList<>();
    secrets.add(options);
    JWTAuth jwtAuth = JWTAuth.create(vertx, (new JWTAuthOptions()).setSecrets(secrets));
    JsonObject jsonObject1 = new JsonObject();
    jsonObject1.put("id", id);
    return jwtAuth.generateToken(jsonObject1, (new JWTOptions()).setExpiresInSeconds(0));
  }
  
  public static void main(String[] args) {
//    JwtUtil jwtUtil = new JwtUtil("12345678");
//    JSONObject jsonObject = new JSONObject();
//    jsonObject.put("id", "123");
//    jsonObject.put("iat", Integer.valueOf(1615862736));
//    String jwt = jwtUtil.createJWT4Subject(jsonObject.toJSONString());
//    String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjEyMyIsImlhdCI6MTYxNTg2MjczNn0.ey7fe3UUuesSCXC4X43YkF4yeAVC_dCT4sZEi4r9Cvo";
//    String signData = getSignData(token);
//    String signData1 = getSignData(jwt);
//    String secretOrKey = "12345678";
//    String ruyingGwt = getRuyingGwt(secretOrKey, "hny");
//    System.out.println(ruyingGwt);
    String jwtToken = JwtUtil.getRuyingGwt("12345678", "863e8dafac9c446293ccf465af2f8296");
    System.out.println(jwtToken);
  }
}
